package layui.controller.user;

import layui.controller.BaseServlet;
import layui.dao.UserDao;
import layui.dao.impl.UserDaoImpl;
import layui.entity.User;
import layui.util.Md5Util;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author zqx
 * @Date 2023-11-15
 */

@WebServlet("/admin/user/user_login")
public class LoginServlet extends BaseServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 第一：获取客户端提交数据
        String uname = req.getParameter("account");
        String upass = req.getParameter("password");

        // 第二：对数据进行合法性验证（略） - 正则表达式
        // 第三：加工处理 - 业务逻辑 - 调用DAO
        UserDao userDao = new UserDaoImpl();
        User user = userDao.selectUser(uname);

        // 第四：响应
        if (user == null) {
            print(resp, errorJson(500, "此用户不存在", null));
            return;
        }

        if (!Md5Util.equals(upass, user.getPassword())) {
            print(resp, errorJson(500, "错误的帐号或密码", null));
            return;
        }

        user.setPassword(null);
        print(resp, successJson(200, "登录成功", user));


    }
}
